<template>
  <div class="astronomical-data-container">
    <div class="data-header">
      <h2 class="section-title">实时天文数据</h2>
      <div class="last-updated">
        最后更新: {{ lastUpdated }}
      </div>
    </div>

    <!-- 数据卡片网格 -->
    <div class="data-cards">
      <!-- ISS位置卡片 -->
      <div class="data-card iss-card">
        <div class="card-header">
          <div class="card-icon">🛰️</div>
          <h3 class="card-title">国际空间站</h3>
        </div>
        <div class="card-content iss-content">
          <div class="iss-location">
            <div class="location-item">
              <span class="label">纬度:</span>
              <span class="value">{{ issData.latitude || '--' }}</span>
            </div>
            <div class="location-item">
              <span class="label">经度:</span>
              <span class="value">{{ issData.longitude || '--' }}</span>
            </div>
            <div class="location-item">
              <span class="label">高度:</span>
              <span class="value">{{ issData.altitude || '--' }} km</span>
            </div>
            <div class="location-item">
              <span class="label">速度:</span>
              <span class="value">{{ issData.velocity || '--' }} km/h</span>
            </div>
          </div>
          <div class="iss-map" ref="issMapRef"></div>
        </div>
      </div>

      <!-- 太阳活动卡片 -->
      <div class="data-card solar-card">
        <div class="card-header">
          <div class="card-icon">☀️</div>
          <h3 class="card-title">太阳活动</h3>
        </div>
        <div class="card-content solar-content">
          <div class="solar-indicators">
            <div class="indicator">
              <div class="indicator-label">太阳黑子数</div>
              <div class="indicator-value">{{ solarData.sunspots || '--' }}</div>
              <div class="indicator-change" :class="solarData.sunspotsTrend || ''">
                {{ getTrendIcon(solarData.sunspotsTrend) }}
              </div>
            </div>
            <div class="indicator">
              <div class="indicator-label">耀斑活动</div>
              <div class="indicator-value">{{ getFlareLevel(solarData.flareLevel) }}</div>
              <div class="flare-intensity" :class="getFlareClass(solarData.flareLevel)"></div>
            </div>
            <div class="indicator">
              <div class="indicator-label">太阳风速度</div>
              <div class="indicator-value">{{ solarData.solarWindSpeed || '--' }} km/s</div>
            </div>
            <div class="indicator">
              <div class="indicator-label">地磁指数</div>
              <div class="indicator-value">{{ solarData.kpIndex || '--' }}</div>
              <div class="kp-indicator" :class="getKpClass(solarData.kpIndex)"></div>
            </div>
          </div>
          <div class="solar-image">
            <div v-if="solarData.imageUrl" class="sun-image">
              <img :src="solarData.imageUrl" alt="太阳图像" @error="handleImageError">
            </div>
            <div v-else class="sun-placeholder">
              <div class="sun-icon">☀️</div>
              <span>加载太阳图像...</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 月球相位卡片 -->
      <div class="data-card moon-card">
        <div class="card-header">
          <div class="card-icon">🌙</div>
          <h3 class="card-title">月球相位</h3>
        </div>
        <div class="card-content moon-content">
          <div class="moon-phase-display">
            <div class="moon-model" ref="moonPhaseRef">
              <div class="moon-sphere" :style="getMoonPhaseStyle()"></div>
            </div>
            <div class="moon-info">
              <div class="phase-name">{{ moonData.phaseName || '--' }}</div>
              <div class="phase-details">
                <div class="detail-item">
                  <span class="label">月龄:</span>
                  <span class="value">{{ moonData.age || '--' }}天</span>
                </div>
                <div class="detail-item">
                  <span class="label">可见度:</span>
                  <span class="value">{{ moonData.illumination || '--' }}%</span>
                </div>
                <div class="detail-item">
                  <span class="label">下一个相位:</span>
                  <span class="value">{{ moonData.nextPhase || '--' }}</span>
                </div>
              </div>
            </div>
          </div>
          <div class="moon-phase-calendar">
            <div class="calendar-dots">
              <div 
                v-for="(day, index) in 30" 
                :key="index"
                class="phase-dot"
                :class="getDotClass(index)"
                :title="getPhaseTitle(index)"
              ></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 观测条件卡片 -->
      <div class="data-card observation-card">
        <div class="card-header">
          <div class="card-icon">🔭</div>
          <h3 class="card-title">观测条件</h3>
        </div>
        <div class="card-content observation-content">
          <!-- 地理位置输入 -->
          <div class="location-input" style="margin-bottom: 1rem; width: 100%;">
            <input 
              type="text" 
              v-model="userLocationInput" 
              placeholder="输入观测地点(如: 北京)或使用当前位置" 
              @keyup.enter="updateLocation"
              class="location-text-input"
            >
            <button @click="updateLocation" class="location-submit-btn">更新</button>
            <button @click="useCurrentLocation" class="location-current-btn">📍</button>
          </div>
          
          <div class="observation-score">
            <div class="score-circle" :class="getScoreClass(observationData.overallScore)">
              <div class="score-number">{{ observationData.overallScore || '--' }}</div>
              <div class="score-label">总分</div>
            </div>
            <div class="score-details">
              <div class="score-item">
                <span class="label">视宁度:</span>
                <span class="value">{{ observationData.seeing || '--' }}</span>
                <span class="unit">/10</span>
              </div>
              <div class="score-item">
                <span class="label">透明度:</span>
                <span class="value">{{ observationData.transparency || '--' }}</span>
                <span class="unit">/10</span>
              </div>
              <div class="score-item">
                <span class="label">光污染:</span>
                <span class="value">{{ observationData.lightPollution || '--' }}</span>
                <span class="unit">(1-9级)</span>
              </div>
              <div class="score-item">
                <span class="label">气象:</span>
                <span class="value">{{ observationData.weather || '--' }}</span>
              </div>
            </div>
            
            <!-- 详细评分影响因素 -->
            <div class="detailed-scores">
              <div class="detailed-score-item">
                <span class="label">湿度:</span>
                <div class="progress-bar">
                  <div class="progress-fill humidity-fill" :style="{ width: observationData.humidityScore + '%' }"></div>
                </div>
                <span class="value">{{ observationData.humidity || '--' }}%</span>
              </div>
              <div class="detailed-score-item">
                <span class="label">风速:</span>
                <div class="progress-bar">
                  <div class="progress-fill wind-fill" :style="{ width: observationData.windScore + '%' }"></div>
                </div>
                <span class="value">{{ observationData.windSpeed || '--' }} m/s</span>
              </div>
              <div class="detailed-score-item">
                <span class="label">温度:</span>
                <div class="progress-bar">
                  <div class="progress-fill temperature-fill" :style="{ width: observationData.temperatureScore + '%' }"></div>
                </div>
                <span class="value">{{ observationData.temperature || '--' }}°C</span>
              </div>
              <div class="detailed-score-item">
                <span class="label">月相干扰:</span>
                <div class="progress-bar">
                  <div class="progress-fill moon-fill" :style="{ width: observationData.moonScore + '%' }"></div>
                </div>
                <span class="value">{{ observationData.moonInterference || '--' }}</span>
              </div>
            </div>
          </div>
          
          <!-- 视宁度可视化区域 -->
          <div class="seeing-container">
            <h4>视宁度实时监测</h4>
            <div class="seeing-content">
              <div class="seeing-value">{{ observationData.seeing || 0 }}/10</div>
              <div class="seeing-waveform" ref="seeingWaveformRef"></div>
              <div class="seeing-info">
                <div class="seeing-status">{{ getSeeingStatus(observationData.seeing || 0) }}</div>
                <div class="seeing-description">{{ getSeeingDescription(observationData.seeing || 0) }}</div>
              </div>
            </div>
          </div>
          
          <div class="light-pollution-map" ref="lightPollutionMapRef">
            <div class="map-placeholder">
              <div class="map-icon">🗺️</div>
              <span>光污染地图</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 最佳观测时间推荐 -->
    <div class="best-time-section">
      <h3 class="section-subtitle">最佳观测时间</h3>
      <div class="best-time-container">
        <div 
          v-for="(timeSlot, index) in bestViewingTimes" 
          :key="index"
          class="time-slot"
          :class="getTimeSlotClass(timeSlot.score)"
        >
          <div class="time-info">
            <div class="time-date">{{ timeSlot.date }}</div>
            <div class="time-range">{{ timeSlot.time }}</div>
          </div>
          <div class="time-score">{{ timeSlot.score }}/10</div>
          <div class="time-conditions">
            <div class="condition-item">
              <span class="condition-icon">🌙</span>
              <span>{{ timeSlot.moonPhase }}</span>
            </div>
            <div class="condition-item">
              <span class="condition-icon">🌤️</span>
              <span>{{ timeSlot.weather }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted, computed, watch } from 'vue'

export default {
  name: 'AstronomicalData',
  props: {
    location: {
      type: Object,
      default: () => ({ latitude: 39.9042, longitude: 116.4074 }) // 默认北京坐标
    }
  },
  setup(props) {
    // 数据状态
    const lastUpdated = ref('加载中...')
    
    // ISS数据
    const issData = reactive({
      latitude: null,
      longitude: null,
      altitude: null,
      velocity: null,
      timestamp: null
    })
    
    // 太阳活动数据
    const solarData = reactive({
      sunspots: null,
      sunspotsTrend: 'stable', // increasing, decreasing, stable
      flareLevel: 0, // 0-5
      solarWindSpeed: null,
      kpIndex: null,
      imageUrl: null
    })
    
    // 月球相位数据
    const moonData = reactive({
      phaseName: null,
      age: null,
      illumination: null,
      nextPhase: null,
      phaseAngle: null
    })
    
    // 用户位置状态
    const userLocationInput = ref('')
    const currentLocation = ref({ ...props.location })
    
    // 观测条件数据
    const observationData = reactive({
      overallScore: null,
      seeing: null,
      transparency: null,
      lightPollution: null,
      weather: null,
      // 详细气象数据
      temperature: null,
      humidity: null,
      windSpeed: null,
      cloudCover: null,
      // 评分因素
      humidityScore: null,
      windScore: null,
      temperatureScore: null,
      moonScore: null,
      cloudScore: null,
      moonInterference: null
    })
    
    // 视宁度波形相关引用和数据
    const seeingWaveformRef = ref(null)
    let seeingAnimationFrame = null
    const seeingWaveformData = reactive({
      amplitude: 0.5,
      frequency: 0.01,
      points: [],
      time: 0,
      animationSpeed: 0.05
    })
    
    // 最佳观测时间
    const bestViewingTimes = ref([])
    
    // 引用
    const issMapRef = ref(null)
    const moonPhaseRef = ref(null)
    const lightPollutionMapRef = ref(null)
    
    // 更新计时器
    let updateInterval = null
    
    // 获取趋势图标
    const getTrendIcon = (trend) => {
      switch(trend) {
        case 'increasing': return '↑'
        case 'decreasing': return '↓'
        default: return '→'
      }
    }
    
    // 获取耀斑等级
    const getFlareLevel = (level) => {
      const levels = ['安静', '低', '中', '高', '活跃', '剧烈']
      return levels[level] || '--'
    }
    
    // 获取耀斑等级样式
    const getFlareClass = (level) => {
      const classes = ['flare-quiet', 'flare-low', 'flare-medium', 'flare-high', 'flare-active', 'flare-severe']
      return classes[level] || ''
    }
    
    // 获取地磁指数样式
    const getKpClass = (kp) => {
      if (kp < 3) return 'kp-low'
      if (kp < 5) return 'kp-medium'
      if (kp < 7) return 'kp-high'
      return 'kp-severe'
    }
    
    // 获取月球相位样式
    const getMoonPhaseStyle = () => {
      const angle = moonData.phaseAngle || 0
      return {
        transform: `rotate(${angle}deg)`
      }
    }
    
    // 获取分数等级样式
    const getScoreClass = (score) => {
      if (score >= 8) return 'score-excellent'
      if (score >= 6) return 'score-good'
      if (score >= 4) return 'score-fair'
      return 'score-poor'
    }
    
    // 获取时间槽样式
    const getTimeSlotClass = (score) => {
      if (score >= 8) return 'slot-excellent'
      if (score >= 6) return 'slot-good'
      if (score >= 4) return 'slot-fair'
      return 'slot-poor'
    }
    
    // 获取相位点样式
    const getDotClass = (day) => {
      // 模拟相位点样式
      const phases = [
        { day: 0, class: 'new-moon' },
        { day: 7, class: 'first-quarter' },
        { day: 15, class: 'full-moon' },
        { day: 22, class: 'last-quarter' }
      ]
      
      const currentDay = Math.floor(moonData.age || 0)
      const phase = phases.find(p => Math.abs(p.day - day) < 1) || { class: '' }
      
      return {
        'phase-dot': true,
        [phase.class]: true,
        'current-day': day === currentDay
      }
    }
    
    // 获取相位标题
    const getPhaseTitle = (day) => {
      // 模拟相位标题
      if (day === 0) return '新月'
      if (day === 7) return '上弦月'
      if (day === 15) return '满月'
      if (day === 22) return '下弦月'
      return `${day}天`
    }
    
    // 处理图像加载错误
    const handleImageError = (event) => {
      event.target.src = ''
      solarData.imageUrl = null
    }
    
    // 更新ISS数据
    const updateISSData = async () => {
      try {
        // 使用公开的ISS位置API获取真实数据
        const response = await fetch('https://api.wheretheiss.at/v1/satellites/25544')
        if (!response.ok) {
          throw new Error(`API响应错误: ${response.status}`)
        }
        const data = await response.json()
        
        issData.latitude = data.latitude.toFixed(4)
        issData.longitude = data.longitude.toFixed(4)
        issData.altitude = data.altitude.toFixed(2)
        // 转换速度单位：km/s 到 km/h
        issData.velocity = (data.velocity * 3600).toFixed(2)
        issData.timestamp = new Date().toISOString()
        
        // 更新地图上的ISS位置
        updateISSPositionOnMap()
        
        updateLastUpdated()
      } catch (error) {
        console.error('更新ISS数据失败:', error)
        // 出错时使用模拟数据作为备用
        issData.latitude = (39.9042 + (Math.random() - 0.5) * 5).toFixed(4)
        issData.longitude = (116.4074 + (Math.random() - 0.5) * 5).toFixed(4)
        issData.altitude = (408 + (Math.random() - 0.5) * 10).toFixed(2)
        issData.velocity = (27600 + (Math.random() - 0.5) * 500).toFixed(2)
      }
    }
    
    // 在地图上更新ISS位置
    const updateISSPositionOnMap = () => {
      if (!issMapRef.value) return
      
      // 清除之前的内容
      issMapRef.value.innerHTML = ''
      
      // 创建简化的世界地图背景
      const mapContainer = document.createElement('div')
      mapContainer.style.width = '100%'
      mapContainer.style.height = '100%'
      mapContainer.style.background = 'linear-gradient(135deg, #1a2a6c 0%, #b21f1f 50%, #fdbb2d 100%)'
      mapContainer.style.borderRadius = '12px'
      mapContainer.style.position = 'relative'
      mapContainer.style.overflow = 'hidden'
      mapContainer.style.backgroundSize = 'cover'
      
      // 添加简单的网格线
      const gridOverlay = document.createElement('div')
      gridOverlay.style.position = 'absolute'
      gridOverlay.style.top = '0'
      gridOverlay.style.left = '0'
      gridOverlay.style.width = '100%'
      gridOverlay.style.height = '100%'
      gridOverlay.style.background = 'repeating-linear-gradient(0deg, transparent, transparent 20px, rgba(255,255,255,0.1) 20px, rgba(255,255,255,0.1) 21px), repeating-linear-gradient(90deg, transparent, transparent 20px, rgba(255,255,255,0.1) 20px, rgba(255,255,255,0.1) 21px)'
      
      // 计算ISS位置在地图上的坐标
      // 将经纬度转换为地图上的百分比位置（简化版本）
      const lat = parseFloat(issData.latitude)
      const lon = parseFloat(issData.longitude)
      
      // 简单的墨卡托投影转换（简化版）
      const x = ((lon + 180) / 360) * 100
      const y = ((90 - lat) / 180) * 100
      
      // 创建ISS标记
      const issMarker = document.createElement('div')
      issMarker.style.position = 'absolute'
      issMarker.style.left = `${x}%`
      issMarker.style.top = `${y}%`
      issMarker.style.transform = 'translate(-50%, -50%)'
      issMarker.style.width = '12px'
      issMarker.style.height = '12px'
      issMarker.style.backgroundColor = 'white'
      issMarker.style.borderRadius = '50%'
      issMarker.style.boxShadow = '0 0 10px 2px rgba(255,255,255,0.8)'
      issMarker.style.zIndex = '10'
      issMarker.style.animation = 'pulse 2s infinite'
      issMarker.title = `ISS位置: ${issData.latitude}, ${issData.longitude}`
      
      // 添加脉冲动画
      const style = document.createElement('style')
      style.textContent = `
        @keyframes pulse {
          0% { transform: translate(-50%, -50%) scale(1); opacity: 1; }
          50% { transform: translate(-50%, -50%) scale(1.5); opacity: 0.7; }
          100% { transform: translate(-50%, -50%) scale(1); opacity: 1; }
        }
      `
      
      // 添加位置标签
      const positionLabel = document.createElement('div')
      positionLabel.style.position = 'absolute'
      positionLabel.style.left = `${x}%`
      positionLabel.style.top = `${y + 5}%`
      positionLabel.style.transform = 'translateX(-50%)'
      positionLabel.style.color = 'white'
      positionLabel.style.fontSize = '10px'
      positionLabel.style.backgroundColor = 'rgba(0,0,0,0.7)'
      positionLabel.style.padding = '2px 6px'
      positionLabel.style.borderRadius = '4px'
      positionLabel.style.zIndex = '10'
      positionLabel.textContent = `${issData.latitude}, ${issData.longitude}`
      
      // 组装地图
      mapContainer.appendChild(gridOverlay)
      mapContainer.appendChild(issMarker)
      mapContainer.appendChild(positionLabel)
      issMapRef.value.appendChild(mapContainer)
      document.head.appendChild(style)
    }
    
    // 更新太阳活动数据
    const updateSolarData = async () => {
      try {
        // 并行请求多个太阳活动数据源
        const requests = [
          fetchSunspotData(),
          fetchFlareData(),
          fetchSpaceWeatherData()
        ]
        
        const [sunspotResult, flareResult, spaceWeatherResult] = await Promise.allSettled(requests)
        
        // 处理太阳黑子数据
        if (sunspotResult.status === 'fulfilled' && sunspotResult.value) {
          solarData.sunspots = sunspotResult.value.count
          solarData.sunspotsTrend = sunspotResult.value.trend
        } else {
          // 备用数据
          solarData.sunspots = Math.floor(Math.random() * 100) + 20
          solarData.sunspotsTrend = ['increasing', 'decreasing', 'stable'][Math.floor(Math.random() * 3)]
        }
        
        // 处理耀斑数据
        if (flareResult.status === 'fulfilled' && flareResult.value) {
          solarData.flareLevel = flareResult.value.level
        } else {
          solarData.flareLevel = Math.floor(Math.random() * 4)
        }
        
        // 处理太空天气数据
        if (spaceWeatherResult.status === 'fulfilled' && spaceWeatherResult.value) {
          solarData.solarWindSpeed = spaceWeatherResult.value.solarWindSpeed
          solarData.kpIndex = spaceWeatherResult.value.kpIndex
        } else {
          solarData.solarWindSpeed = Math.floor(Math.random() * 300) + 300
          solarData.kpIndex = (Math.random() * 5 + 1).toFixed(1)
        }
        
        // 获取最新的太阳图像
        await fetchSolarImage()
        
        updateLastUpdated()
      } catch (error) {
        console.error('更新太阳活动数据失败:', error)
        // 出错时使用模拟数据
        solarData.sunspots = Math.floor(Math.random() * 100) + 20
        solarData.sunspotsTrend = ['increasing', 'decreasing', 'stable'][Math.floor(Math.random() * 3)]
        solarData.flareLevel = Math.floor(Math.random() * 4)
        solarData.solarWindSpeed = Math.floor(Math.random() * 300) + 300
        solarData.kpIndex = (Math.random() * 5 + 1).toFixed(1)
      }
    }
    
    // 获取太阳黑子数据
    const fetchSunspotData = async () => {
      try {
        // 使用NOAA的太阳黑子数据API
        const response = await fetch('https://services.swpc.noaa.gov/json/solar-cycle/sunspots.json')
        if (!response.ok) throw new Error('无法获取太阳黑子数据')
        
        const data = await response.json()
        if (!data || data.length < 2) throw new Error('太阳黑子数据不足')
        
        // 获取最新数据
        const latest = data[data.length - 1]
        const previous = data[data.length - 2]
        
        // 计算趋势
        let trend = 'stable'
        if (latest.ssn > previous.ssn * 1.1) trend = 'increasing'
        else if (latest.ssn < previous.ssn * 0.9) trend = 'decreasing'
        
        return {
          count: latest.ssn,
          trend: trend
        }
      } catch (error) {
        console.warn('获取太阳黑子数据失败，使用备用数据:', error)
        // 返回模拟数据作为备用
        return {
          count: Math.floor(Math.random() * 100) + 20,
          trend: ['increasing', 'decreasing', 'stable'][Math.floor(Math.random() * 3)]
        }
      }
    }
    
    // 获取耀斑数据
    const fetchFlareData = async () => {
      try {
        // 使用NOAA的耀斑事件API
        const response = await fetch('https://services.swpc.noaa.gov/json/goes/primary/xray-flares-latest.json')
        if (!response.ok) throw new Error('无法获取耀斑数据')
        
        const data = await response.json()
        if (!data || data.length === 0) {
          // 没有耀斑事件
          return { level: 0 }
        }
        
        // 获取最近24小时内的最大耀斑级别
        const recentFlares = data.filter(flare => {
          const flareTime = new Date(flare.begin_time)
          const hoursDiff = (new Date() - flareTime) / (1000 * 60 * 60)
          return hoursDiff <= 24
        })
        
        if (recentFlares.length === 0) {
          return { level: 0 }
        }
        
        // 确定耀斑级别
        // C级=1, M级=2, X级=3-5（根据强度）
        const maxFlare = recentFlares.reduce((max, flare) => {
          return flare.class > max.class ? flare : max
        }, recentFlares[0])
        
        let level = 0
        const flareClass = maxFlare.class
        if (flareClass.startsWith('C')) level = 1
        else if (flareClass.startsWith('M')) level = 2
        else if (flareClass.startsWith('X')) {
          const intensity = parseFloat(flareClass.substring(1))
          if (intensity < 1) level = 3
          else if (intensity < 10) level = 4
          else level = 5
        }
        
        return { level: level }
      } catch (error) {
        console.warn('获取耀斑数据失败，使用备用数据:', error)
        return { level: Math.floor(Math.random() * 4) }
      }
    }
    
    // 获取太空天气数据
    const fetchSpaceWeatherData = async () => {
      try {
        // 使用NOAA的实时太空天气数据API
        const response = await fetch('https://services.swpc.noaa.gov/json/geospace/propagated-solar-wind-1-hour.json')
        if (!response.ok) throw new Error('无法获取太空天气数据')
        
        const data = await response.json()
        if (!data || data.length === 0) throw new Error('太空天气数据不足')
        
        const latest = data[data.length - 1]
        
        // 获取Kp指数（从另一个API）
        let kpIndex = '0.0'
        try {
          const kpResponse = await fetch('https://services.swpc.noaa.gov/json/planetary_k_index_1m.json')
          if (kpResponse.ok) {
            const kpData = await kpResponse.json()
            if (kpData && kpData.length > 0) {
              kpIndex = kpData[kpData.length - 1].kp.toFixed(1)
            }
          }
        } catch (kpError) {
          console.warn('获取Kp指数失败:', kpError)
        }
        
        return {
          solarWindSpeed: Math.floor(latest.speed),
          kpIndex: kpIndex
        }
      } catch (error) {
        console.warn('获取太空天气数据失败，使用备用数据:', error)
        return {
          solarWindSpeed: Math.floor(Math.random() * 300) + 300,
          kpIndex: (Math.random() * 5 + 1).toFixed(1)
        }
      }
    }
    
    // 获取太阳图像
    const fetchSolarImage = async () => {
      try {
        // 使用NASA的SDO卫星最新太阳图像
        // 注意：这些API可能会有访问限制或变化
        const imageUrl = 'https://soho.nascom.nasa.gov/data/realtime/hmi_igr/1024/latest.jpg'
        
        // 检查图像是否可访问
        const response = await fetch(imageUrl, { method: 'HEAD' })
        if (response.ok) {
          solarData.imageUrl = imageUrl
        } else {
          // 使用备用图像源
          solarData.imageUrl = 'https://sdo.gsfc.nasa.gov/assets/img/latest/latest_1024_0171.jpg'
        }
      } catch (error) {
        console.warn('获取太阳图像失败:', error)
        // 出错时不设置图像，使用占位符
        solarData.imageUrl = null
      }
    }
    
    // 更新月球相位数据
    const updateMoonData = async () => {
      try {
        // 尝试使用NASA的月球相位API
        let moonDataResult = null
        try {
          const response = await fetch('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY')
          if (response.ok) {
            // NASA的APOD API有时会返回月球相关数据，但不直接提供相位信息
            // 我们将主要使用天文算法计算
            await response.json()
          }
        } catch (apiError) {
          console.warn('NASA API调用失败，使用天文算法计算:', apiError)
        }
        
        // 使用精确的天文算法计算月球相位
        const now = new Date()
        const phaseInfo = calculateMoonPhase(now)
        
        moonData.age = phaseInfo.ageOfMoon.toFixed(1)
        moonData.illumination = Math.floor(phaseInfo.illumination * 100)
        moonData.phaseName = phaseInfo.phaseName
        moonData.phaseAngle = phaseInfo.phaseAngle
        moonData.nextPhase = phaseInfo.nextPhaseString
        
        // 初始化月球3D可视化
        initMoonVisualization()
        
        updateLastUpdated()
      } catch (error) {
        console.error('更新月球相位数据失败:', error)
        // 出错时使用简化计算作为备用
        const age = (new Date().getTime() / (1000 * 60 * 60 * 24)) % 29.53
        moonData.age = age.toFixed(1)
        moonData.illumination = Math.floor(Math.sin((age / 29.53) * Math.PI) * 100)
        const phaseNames = ['新月', '眉月', '上弦月', '盈凸月', '满月', '亏凸月', '下弦月', '残月']
        moonData.phaseName = phaseNames[Math.floor((age / 29.53) * 8)]
        moonData.phaseAngle = (age / 29.53) * 360
      }
    }
    
    // 使用天文算法精确计算月球相位
    const calculateMoonPhase = (date) => {
      // 简化的月球相位计算算法
      // 基于Jean Meeus的天文算法
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      
      // 计算从2000年1月1日起的天数
      const daysSince2000 = calculateDaysSince2000(year, month, day)
      
      // 月球平均轨道周期
      const synodicMonth = 29.530588861
      
      // 计算月龄（从新月开始的天数）
      const ageOfMoon = daysSince2000 % synodicMonth
      
      // 计算相位角（0-360度）
      const phaseAngle = (ageOfMoon / synodicMonth) * 360
      
      // 计算月相照明百分比（基于相位角）
      // 新月时为0%，满月时为100%
      const illumination = 0.5 * (1 - Math.cos((phaseAngle * Math.PI) / 180))
      
      // 确定月相名称
      let phaseName = ''
      if (ageOfMoon < 1.5) phaseName = '新月'
      else if (ageOfMoon < 6.5) phaseName = '眉月'
      else if (ageOfMoon < 10.5) phaseName = '上弦月'
      else if (ageOfMoon < 14.5) phaseName = '盈凸月'
      else if (ageOfMoon < 16.5) phaseName = '满月'
      else if (ageOfMoon < 21.5) phaseName = '亏凸月'
      else if (ageOfMoon < 25.5) phaseName = '下弦月'
      else phaseName = '残月'
      
      // 计算下一个主要相位
      let nextPhaseDay = 0
      let nextPhaseName = ''
      
      if (ageOfMoon < 1.5) {
        nextPhaseDay = 6.5 - ageOfMoon
        nextPhaseName = '眉月'
      } else if (ageOfMoon < 6.5) {
        nextPhaseDay = 10.5 - ageOfMoon
        nextPhaseName = '上弦月'
      } else if (ageOfMoon < 10.5) {
        nextPhaseDay = 14.5 - ageOfMoon
        nextPhaseName = '盈凸月'
      } else if (ageOfMoon < 14.5) {
        nextPhaseDay = 16.5 - ageOfMoon
        nextPhaseName = '满月'
      } else if (ageOfMoon < 16.5) {
        nextPhaseDay = 21.5 - ageOfMoon
        nextPhaseName = '亏凸月'
      } else if (ageOfMoon < 21.5) {
        nextPhaseDay = 25.5 - ageOfMoon
        nextPhaseName = '下弦月'
      } else if (ageOfMoon < 25.5) {
        nextPhaseDay = 29.53 - ageOfMoon
        nextPhaseName = '残月'
      } else {
        nextPhaseDay = synodicMonth - ageOfMoon + 1.5
        nextPhaseName = '新月'
      }
      
      const nextPhaseString = nextPhaseDay < 1 
        ? `${Math.ceil(nextPhaseDay * 24)}小时后 ${nextPhaseName}`
        : `${Math.ceil(nextPhaseDay)}天后 ${nextPhaseName}`
      
      return {
        ageOfMoon,
        illumination,
        phaseAngle,
        phaseName,
        nextPhaseString
      }
    }
    
    // 计算从2000年1月1日起的天数
    const calculateDaysSince2000 = (year, month, day) => {
      // 简化计算，实际天文计算需要更精确的公式
      const date = new Date(year, month - 1, day)
      const epoch = new Date(2000, 0, 1)
      const diffTime = date - epoch
      return diffTime / (1000 * 60 * 60 * 24)
    }
    
    // 初始化月球3D可视化
    const initMoonVisualization = () => {
      if (!moonPhaseRef.value) return
      
      // 清除之前的内容
      moonPhaseRef.value.innerHTML = ''
      
      // 创建3D月球容器
      const moonContainer = document.createElement('div')
      moonContainer.style.width = '150px'
      moonContainer.style.height = '150px'
      moonContainer.style.position = 'relative'
      moonContainer.style.display = 'flex'
      moonContainer.style.alignItems = 'center'
      moonContainer.style.justifyContent = 'center'
      
      // 创建月球球体
      const moonSphere = document.createElement('div')
      moonSphere.style.width = '120px'
      moonSphere.style.height = '120px'
      moonSphere.style.borderRadius = '50%'
      moonSphere.style.position = 'relative'
      
      // 设置月球表面纹理（使用CSS渐变模拟）
      moonSphere.style.background = `radial-gradient(circle at 30% 30%, #f0e6d2 0%, #d3c7a6 20%, #a69c83 50%, #8c8068 80%, #665a45 100%)`
      moonSphere.style.boxShadow = 'inset 0 0 30px rgba(0, 0, 0, 0.3)'
      
      // 添加月球表面的细节（使用伪元素和CSS生成）
      const moonDetails = document.createElement('div')
      moonDetails.style.position = 'absolute'
      moonDetails.style.width = '100%'
      moonDetails.style.height = '100%'
      moonDetails.style.borderRadius = '50%'
      moonDetails.style.overflow = 'hidden'
      
      // 创建月海和环形山（简化版）
      const createMoonFeature = (size, top, left, opacity, blur) => {
        const feature = document.createElement('div')
        feature.style.position = 'absolute'
        feature.style.width = `${size}px`
        feature.style.height = `${size}px`
        feature.style.top = `${top}%`
        feature.style.left = `${left}%`
        feature.style.transform = 'translate(-50%, -50%)'
        feature.style.borderRadius = '50%'
        feature.style.background = 'rgba(0, 0, 0, 0.1)'
        feature.style.boxShadow = `inset 0 0 ${blur}px rgba(0, 0, 0, ${opacity})`
        return feature
      }
      
      // 添加一些月球表面特征
      const features = [
        { size: 40, top: 25, left: 30, opacity: 0.2, blur: 5 },  // 风暴洋
        { size: 25, top: 60, left: 40, opacity: 0.15, blur: 3 }, // 雨海
        { size: 20, top: 40, left: 65, opacity: 0.15, blur: 3 }, // 静海
        { size: 15, top: 75, left: 70, opacity: 0.1, blur: 2 },  // 澄海
        { size: 10, top: 30, left: 80, opacity: 0.1, blur: 2 },  // 危海
        { size: 8, top: 50, left: 15, opacity: 0.15, blur: 2 },  // 酒海
        { size: 5, top: 80, left: 30, opacity: 0.1, blur: 1 },   // 小环形山
        { size: 4, top: 40, left: 10, opacity: 0.1, blur: 1 },   // 小环形山
        { size: 6, top: 15, left: 50, opacity: 0.1, blur: 1 }    // 小环形山
      ]
      
      features.forEach(feature => {
        moonDetails.appendChild(createMoonFeature(
          feature.size, feature.top, feature.left, feature.opacity, feature.blur
        ))
      })
      
      // 创建阴影来表示月相
      const shadow = document.createElement('div')
      shadow.style.position = 'absolute'
      shadow.style.width = '100%'
      shadow.style.height = '100%'
      shadow.style.borderRadius = '50%'
      shadow.style.pointerEvents = 'none'
      
      // 根据月相设置阴影
      updateMoonShadow(shadow)
      
      // 添加月球光晕效果
      const glow = document.createElement('div')
      glow.style.position = 'absolute'
      glow.style.width = '130%'
      glow.style.height = '130%'
      glow.style.borderRadius = '50%'
      glow.style.background = 'radial-gradient(circle, rgba(255,255,240,0.2) 0%, transparent 70%)'
      glow.style.pointerEvents = 'none'
      
      // 组装月球可视化
      moonSphere.appendChild(moonDetails)
      moonSphere.appendChild(shadow)
      moonContainer.appendChild(moonSphere)
      moonContainer.appendChild(glow)
      
      // 添加到DOM
      moonPhaseRef.value.appendChild(moonContainer)
      
      // 添加旋转动画
      const style = document.createElement('style')
      style.textContent = `
        @keyframes moon-rotate {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
        .moon-rotate-slow {
          animation: moon-rotate 120s linear infinite;
        }
      `
      document.head.appendChild(style)
      
      // 应用旋转动画
      moonSphere.classList.add('moon-rotate-slow')
    }
    
    // 根据月相更新阴影
    const updateMoonShadow = (shadowElement) => {
      const phase = moonData.phaseAngle || 0
      let shadowStyle = ''
      
      if (phase < 90) {
        // 新月到上弦月
        const percentage = phase / 90
        shadowStyle = `linear-gradient(90deg, rgba(0,0,0,0.7) 0%, rgba(0,0,0,0.7) ${100 - percentage * 100}%, transparent 100%)`
      } else if (phase < 180) {
        // 上弦月到满月
        const percentage = (phase - 90) / 90
        shadowStyle = `linear-gradient(90deg, transparent 0%, transparent ${percentage * 100}%, rgba(0,0,0,0.7) 100%)`
      } else if (phase < 270) {
        // 满月到下弦月
        const percentage = (phase - 180) / 90
        shadowStyle = `linear-gradient(90deg, transparent 0%, transparent ${100 - percentage * 100}%, rgba(0,0,0,0.7) 100%)`
      } else {
        // 下弦月到新月
        const percentage = (phase - 270) / 90
        shadowStyle = `linear-gradient(90deg, rgba(0,0,0,0.7) 0%, rgba(0,0,0,0.7) ${percentage * 100}%, transparent 100%)`
      }
      
      shadowElement.style.background = shadowStyle
    }
    
    // 获取气象数据
    const fetchWeatherData = async (lat, lon) => {
      try {
        // 使用OpenWeatherMap API获取气象数据（需要替换为实际的API密钥）
        const apiKey = 'YOUR_OPENWEATHER_API_KEY'; // 注意：实际使用时需要配置真实API密钥
        const response = await fetch(
          `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric&lang=zh_cn`
        );
        
        if (!response.ok) throw new Error('气象数据获取失败');
        return await response.json();
      } catch (error) {
        console.warn('获取气象数据失败，使用模拟数据:', error);
        // 返回模拟气象数据
        return {
          main: {
            temp: 20 + (Math.random() * 10 - 5),
            humidity: 40 + Math.random() * 40
          },
          wind: {
            speed: 1 + Math.random() * 5
          },
          clouds: {
            all: Math.random() * 100
          },
          weather: [{
            main: ['Clear', 'Clouds', 'Few Clouds'][Math.floor(Math.random() * 3)],
            description: ['晴朗', '多云', '少云'][Math.floor(Math.random() * 3)]
          }]
        };
      }
    }
    
    // 获取光污染数据
    const fetchLightPollutionData = async (lat, lon) => {
      try {
        // 这里可以集成光污染API，如Globe at Night或Light Pollution Map的数据
        // 目前返回模拟数据
        const levels = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // 1-9级，1最暗，9最亮
        return levels[Math.floor(Math.random() * 5)]; // 模拟1-5级较常见
      } catch (error) {
        console.warn('获取光污染数据失败:', error);
        return 3; // 默认中等光污染
      }
    }
    
    // 计算湿度评分（湿度越低越好，0-100%）
    const calculateHumidityScore = (humidity) => {
      // 湿度<30%: 最佳(100分)
      // 30-50%: 良好(80-100分)
      // 50-70%: 一般(60-80分)
      // 70-85%: 较差(40-60分)
      // >85%: 很差(0-40分)
      if (humidity < 30) return 100;
      if (humidity < 50) return 100 - (humidity - 30) * 1;
      if (humidity < 70) return 80 - (humidity - 50) * 1;
      if (humidity < 85) return 60 - (humidity - 70) * 1.33;
      return Math.max(0, 40 - (humidity - 85) * 2.67);
    }
    
    // 计算风速评分（风速适中最好，0-20 m/s）
    const calculateWindScore = (windSpeed) => {
      // 0-5 m/s: 良好(80-100分)
      // 5-10 m/s: 一般(60-80分)
      // >10 m/s: 较差(0-60分)
      if (windSpeed < 5) return 100 - windSpeed * 4;
      if (windSpeed < 10) return 80 - (windSpeed - 5) * 4;
      return Math.max(0, 60 - (windSpeed - 10) * 6);
    }
    
    // 计算温度评分（适中温度最好，-10到40°C）
    const calculateTemperatureScore = (temp) => {
      // 5-20°C: 最佳(100分)
      // 0-5°C或20-25°C: 良好(80-100分)
      // -10-0°C或25-35°C: 一般(60-80分)
      // >35°C或<-10°C: 较差(0-60分)
      if (temp >= 5 && temp <= 20) return 100;
      if (temp >= 0 && temp < 5) return 100 - (5 - temp) * 4;
      if (temp > 20 && temp <= 25) return 100 - (temp - 20) * 4;
      if (temp >= -10 && temp < 0) return 80 - Math.abs(temp) * 2;
      if (temp > 25 && temp <= 35) return 80 - (temp - 25) * 2;
      return Math.max(0, 60 - Math.max(0, temp - 35, -10 - temp) * 3);
    }
    
    // 计算云量评分（云量越少越好，0-100%）
    const calculateCloudScore = (cloudCover) => {
      // 0-10%: 晴朗(100分)
      // 10-30%: 少云(80-100分)
      // 30-70%: 多云(40-80分)
      // >70%: 阴天(0-40分)
      if (cloudCover < 10) return 100;
      if (cloudCover < 30) return 100 - (cloudCover - 10) * 1;
      if (cloudCover < 70) return 80 - (cloudCover - 30) * 1;
      return Math.max(0, 40 - (cloudCover - 70) * 1.33);
    }
    
    // 计算月相评分（基于月球可见度，可见度越低越好）
    const calculateMoonScore = (illumination) => {
      // 0-10%: 新月期(100分)
      // 10-30%: 眉月/残月(80-100分)
      // 30-70%: 弦月期(60-80分)
      // 70-90%: 凸月期(40-60分)
      // >90%: 满月期(0-40分)
      if (illumination < 10) return 100;
      if (illumination < 30) return 100 - (illumination - 10) * 1;
      if (illumination < 70) return 80 - (illumination - 30) * 0.5;
      if (illumination < 90) return 60 - (illumination - 70) * 1;
      return Math.max(0, 40 - (illumination - 90) * 4);
    }
    
    // 计算光污染评分（等级越低越好，1-9级）
    const calculateLightPollutionScore = (lightPollution) => {
      // 1-2级: 极佳(90-100分)
      // 3-4级: 良好(70-90分)
      // 5-6级: 一般(50-70分)
      // 7-8级: 较差(30-50分)
      // 9级: 很差(0-30分)
      if (lightPollution <= 2) return 100 - (lightPollution - 1) * 10;
      if (lightPollution <= 4) return 90 - (lightPollution - 2) * 10;
      if (lightPollution <= 6) return 70 - (lightPollution - 4) * 10;
      if (lightPollution <= 8) return 50 - (lightPollution - 6) * 10;
      return 30 - (lightPollution - 8) * 30;
    }
    
    // 计算视宁度（基于温度、风速、湿度综合评分）
    const calculateSeeing = (tempScore, windScore, humidityScore) => {
      // 视宁度 = (温度评分 * 0.4 + 风速评分 * 0.4 + 湿度评分 * 0.2) / 10
      const seeing = (tempScore * 0.4 + windScore * 0.4 + humidityScore * 0.2) / 10;
      return Math.round(seeing * 10) / 10; // 保留一位小数
    }
    
    // 计算透明度（基于湿度、云量评分）
    const calculateTransparency = (humidityScore, cloudScore) => {
      // 透明度 = (湿度评分 * 0.5 + 云量评分 * 0.5) / 10
      const transparency = (humidityScore * 0.5 + cloudScore * 0.5) / 10;
      return Math.round(transparency * 10) / 10; // 保留一位小数
    }
    
    // 计算综合评分
    const calculateOverallScore = (seeing, transparency, lightPollutionScore, moonScore) => {
      // 综合评分 = 视宁度 * 0.3 + 透明度 * 0.3 + 光污染评分/10 * 0.25 + 月相评分/10 * 0.15
      const score = seeing * 0.3 + transparency * 0.3 + (lightPollutionScore / 10) * 0.25 + (moonScore / 10) * 0.15;
      return Math.round(score * 10) / 10; // 保留一位小数
    }
    
    // 获取月相干扰描述
    const getMoonInterferenceDescription = (illumination) => {
      if (illumination < 10) return '无干扰';
      if (illumination < 30) return '轻微干扰';
      if (illumination < 70) return '中等干扰';
      if (illumination < 90) return '明显干扰';
      return '严重干扰';
    }
    
    // 获取气象描述
    const getWeatherDescription = (cloudCover) => {
      if (cloudCover < 10) return '晴朗';
      if (cloudCover < 30) return '少云';
      if (cloudCover < 70) return '多云';
      return '阴天';
    }
    
    // 获取视宁度状态
    const getSeeingStatus = (seeing) => {
      if (seeing >= 9) return '极佳';
      if (seeing >= 8) return '优秀';
      if (seeing >= 7) return '良好';
      if (seeing >= 6) return '一般';
      if (seeing >= 5) return '较差';
      return '很差';
    }
    
    // 获取视宁度描述
    const getSeeingDescription = (seeing) => {
      if (seeing >= 9) return '大气极其稳定，适合高精度观测';
      if (seeing >= 8) return '大气稳定，适合拍摄行星和深空天体';
      if (seeing >= 7) return '大气状况良好，观测体验佳';
      if (seeing >= 6) return '大气有轻微抖动，适合一般观测';
      if (seeing >= 5) return '大气抖动明显，观测效果较差';
      return '大气严重抖动，不适合天体观测';
    }
    
    // 生成视宁度波形数据
    const generateWaveform = () => {
      const points = [];
      const width = seeingWaveformRef.value?.offsetWidth || 300;
      const height = seeingWaveformRef.value?.offsetHeight || 100;
      const centerY = height / 2;
      
      // 根据视宁度调整振幅和频率
      const seeing = observationData.seeing || 5;
      const adjustedAmplitude = (10 - seeing) * 0.05; // 视宁度越低，波形越不稳定
      const adjustedFrequency = seeing * 0.002; // 视宁度越高，频率越低
      
      // 生成波形点
      for (let x = 0; x <= width; x++) {
        // 添加多个频率的正弦波以模拟真实的大气波动
        let y = 0;
        y += Math.sin(seeingWaveformData.time + x * adjustedFrequency) * adjustedAmplitude;
        y += Math.sin(seeingWaveformData.time * 1.5 + x * adjustedFrequency * 1.3) * adjustedAmplitude * 0.5;
        y += Math.sin(seeingWaveformData.time * 0.8 + x * adjustedFrequency * 0.7) * adjustedAmplitude * 0.3;
        
        // 添加随机噪声模拟大气湍流
        const noise = (Math.random() - 0.5) * adjustedAmplitude * 0.5;
        y += noise;
        
        // 限制振幅范围
        y = Math.max(-0.5, Math.min(0.5, y));
        
        points.push({
          x,
          y: centerY + y * height * 0.4
        });
      }
      
      seeingWaveformData.points = points;
    }
    
    // 绘制视宁度波形
    const drawWaveform = () => {
      if (!seeingWaveformRef.value) return;
      
      const canvas = seeingWaveformRef.value;
      const ctx = canvas.getContext('2d');
      const width = canvas.offsetWidth;
      const height = canvas.offsetHeight;
      
      // 设置canvas尺寸
      canvas.width = width;
      canvas.height = height;
      
      // 清空画布
      ctx.clearRect(0, 0, width, height);
      
      // 绘制波形
      ctx.beginPath();
      ctx.moveTo(seeingWaveformData.points[0].x, seeingWaveformData.points[0].y);
      
      for (let i = 1; i < seeingWaveformData.points.length; i++) {
        ctx.lineTo(seeingWaveformData.points[i].x, seeingWaveformData.points[i].y);
      }
      
      // 设置波形样式
      const seeing = observationData.seeing || 5;
      let color = '#f44336'; // 红色表示较差
      if (seeing >= 5) color = '#ff9800'; // 橙色
      if (seeing >= 6) color = '#ffeb3b'; // 黄色
      if (seeing >= 7) color = '#8bc34a'; // 浅绿色
      if (seeing >= 8) color = '#4caf50'; // 绿色
      if (seeing >= 9) color = '#00bcd4'; // 青色
      
      ctx.strokeStyle = color;
      ctx.lineWidth = 2;
      ctx.stroke();
      
      // 绘制中心线
      ctx.beginPath();
      ctx.moveTo(0, height / 2);
      ctx.lineTo(width, height / 2);
      ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
      ctx.lineWidth = 1;
      ctx.setLineDash([5, 5]);
      ctx.stroke();
      ctx.setLineDash([]);
    }
    
    // 动画循环
    const animateWaveform = () => {
      seeingWaveformData.time += seeingWaveformData.animationSpeed;
      generateWaveform();
      drawWaveform();
      seeingAnimationFrame = requestAnimationFrame(animateWaveform);
    }
    
    // 初始化视宁度可视化
    const initSeeingVisualization = () => {
      if (seeingWaveformRef.value) {
        // 创建canvas元素
        const canvas = document.createElement('canvas');
        canvas.className = 'seeing-canvas';
        seeingWaveformRef.value.innerHTML = '';
        seeingWaveformRef.value.appendChild(canvas);
        
        // 开始动画
        animateWaveform();
      }
    }
    
    // 更新观测条件数据
    const updateObservationData = async () => {
      try {
        const { latitude, longitude } = currentLocation.value;
        
        // 并行获取数据
        const [weatherData, lightPollution] = await Promise.all([
          fetchWeatherData(latitude, longitude),
          fetchLightPollutionData(latitude, longitude)
        ]);
        
        // 提取气象数据
        const temperature = Math.round(weatherData.main.temp);
        const humidity = Math.round(weatherData.main.humidity);
        const windSpeed = Math.round(weatherData.wind.speed * 10) / 10; // 保留一位小数
        const cloudCover = weatherData.clouds.all;
        
        // 计算各项评分
        const humidityScore = Math.round(calculateHumidityScore(humidity));
        const windScore = Math.round(calculateWindScore(windSpeed));
        const temperatureScore = Math.round(calculateTemperatureScore(temperature));
        const cloudScore = Math.round(calculateCloudScore(cloudCover));
        const lightPollutionScore = Math.round(calculateLightPollutionScore(lightPollution));
        const moonScore = Math.round(calculateMoonScore(moonData.illumination || 0));
        
        // 计算视宁度和透明度
        const seeing = calculateSeeing(temperatureScore, windScore, humidityScore);
        const transparency = calculateTransparency(humidityScore, cloudScore);
        
        // 计算综合评分
        const overallScore = calculateOverallScore(seeing, transparency, lightPollutionScore, moonScore);
        
        // 更新观测数据
        observationData.temperature = temperature;
        observationData.humidity = humidity;
        observationData.windSpeed = windSpeed;
        observationData.cloudCover = cloudCover;
        observationData.lightPollution = lightPollution;
        observationData.weather = getWeatherDescription(cloudCover);
        observationData.seeing = seeing;
        observationData.transparency = transparency;
        observationData.overallScore = overallScore;
        
        // 更新评分因素
        observationData.humidityScore = humidityScore;
        observationData.windScore = windScore;
        observationData.temperatureScore = temperatureScore;
        observationData.cloudScore = cloudScore;
        observationData.moonScore = moonScore;
        observationData.moonInterference = getMoonInterferenceDescription(moonData.illumination || 0);
        
        updateLastUpdated();
      } catch (error) {
        console.error('更新观测条件数据失败:', error);
        // 失败时使用模拟数据
        const score = Math.floor(Math.random() * 4) + 6;
        observationData.overallScore = score;
        observationData.seeing = (Math.random() * 5 + 5).toFixed(1);
        observationData.transparency = (Math.random() * 5 + 5).toFixed(1);
        observationData.lightPollution = Math.floor(Math.random() * 4) + 1;
        observationData.weather = ['晴朗', '少云', '多云', '阴天'][Math.floor(Math.random() * 4)];
        
        // 更新光污染地图
        if (lightPollutionMapRef.value) {
          initLightPollutionMap();
        }
      }
    }
    
    // 更新位置
    const updateLocation = async () => {
      if (!userLocationInput.value.trim()) return;
      
      try {
        // 这里可以调用地理编码API将地点名称转换为坐标
        // 由于API限制，目前使用模拟数据
        const locations = {
          '北京': { latitude: 39.9042, longitude: 116.4074 },
          '上海': { latitude: 31.2304, longitude: 121.4737 },
          '广州': { latitude: 23.1291, longitude: 113.2644 },
          '深圳': { latitude: 22.5431, longitude: 114.0579 },
          '成都': { latitude: 30.5728, longitude: 104.0668 },
          '杭州': { latitude: 30.2741, longitude: 120.1551 },
          '武汉': { latitude: 30.5928, longitude: 114.3055 },
          '西安': { latitude: 34.3416, longitude: 108.9398 }
        };
        
        const city = userLocationInput.value.trim();
        if (locations[city]) {
          currentLocation.value = locations[city];
        } else {
          // 随机位置作为默认
          currentLocation.value = {
            latitude: 30 + (Math.random() * 10 - 5),
            longitude: 110 + (Math.random() * 15 - 7.5)
          };
        }
        
        // 立即更新观测数据
        await updateObservationData();
        // 位置变化后更新地图
        if (lightPollutionMapRef.value) {
          initLightPollutionMap();
        }
      } catch (error) {
        console.error('更新位置失败:', error);
      }
    }
    
    // 使用当前位置
    const useCurrentLocation = () => {
      if ('geolocation' in navigator) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            currentLocation.value = {
              latitude: position.coords.latitude,
              longitude: position.coords.longitude
            };
            // 立即更新观测数据
            updateObservationData();
            // 位置变化后更新地图
            if (lightPollutionMapRef.value) {
              initLightPollutionMap();
            }
          },
          (error) => {
            console.error('获取当前位置失败:', error);
            // 失败时保持默认位置
          }
        );
      }
    }
    
    // 更新最佳观测时间
    const updateBestViewingTimes = async () => {
      const times = []
      const today = new Date()
      const { latitude, longitude } = currentLocation.value
      
      // 生成未来7天的观测时间推荐
      for (let i = 0; i < 7; i++) {
        const date = new Date(today)
        date.setDate(date.getDate() + i)
        
        // 计算该日期的月球相位
        const moonAge = calculateMoonAge(date)
        const moonPhase = getMoonPhaseName(moonAge)
        const moonIllumination = calculateMoonIllumination(moonAge)
        
        // 计算白天/夜晚时间（基于简单估算）
        const isNorthernHemisphere = latitude > 0
        const isSummer = (date.getMonth() >= 3 && date.getMonth() <= 8) === isNorthernHemisphere
        const nightStartHour = isSummer ? 20 : 18 // 夏季晚上开始晚，冬季开始早
        const nightEndHour = isSummer ? 5 : 6 // 夏季早上结束早，冬季结束晚
        
        // 为每个日期生成多个可能的观测时间段
        const timeSlots = generateTimeSlots(date, nightStartHour, nightEndHour)
        
        for (const slot of timeSlots) {
          try {
            // 估算天气条件（真实应用中应从天气预报API获取）
            const estimatedWeather = estimateWeather(date, slot.startHour)
            
            // 计算各因素评分
            const moonScore = Math.round(calculateMoonScore(moonIllumination))
            const lightPollutionScore = Math.round(calculateLightPollutionScore(observationData.lightPollution || 3))
            const weatherScore = calculateWeatherScore(estimatedWeather)
            const hourScore = calculateHourScore(slot.startHour, nightStartHour, nightEndHour)
            
            // 计算综合评分（加权平均）
            const score = Math.round(
              moonScore * 0.3 + // 月球因素影响较大
              lightPollutionScore * 0.3 + // 光污染是重要因素
              weatherScore * 0.3 + // 天气条件也很重要
              hourScore * 0.1 // 时间点的权重稍低
            )
            
            // 只添加评分较高的时间槽（6分以上）
            if (score >= 6) {
              times.push({
                date: date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' }),
                time: `${formatHour(slot.startHour)}-${formatHour(slot.endHour)}`,
                score,
                moonPhase,
                weather: estimatedWeather,
                moonIllumination,
                hourRange: { start: slot.startHour, end: slot.endHour }
              })
            }
          } catch (error) {
            console.error(`计算日期 ${date.toDateString()} 时间 ${slot.startHour}:00 的评分失败:`, error)
          }
        }
      }
      
      // 按分数排序，取前6个最佳时间
      times.sort((a, b) => b.score - a.score)
      bestViewingTimes.value = times.slice(0, 6)
      
      console.log('最佳观测时间已更新:', bestViewingTimes.value)
    }
    
    // 生成观测时间段
    const generateTimeSlots = (date, nightStartHour, nightEndHour) => {
      const slots = []
      
      // 处理跨午夜的情况
      if (nightEndHour < nightStartHour) {
        // 生成晚上到午夜的时间段
        for (let hour = nightStartHour; hour < 24; hour += 2) {
          if (hour + 1 < 24) {
            slots.push({ startHour: hour, endHour: hour + 2 })
          }
        }
        // 生成午夜到黎明的时间段
        for (let hour = 0; hour < nightEndHour; hour += 2) {
          if (hour + 2 <= nightEndHour) {
            slots.push({ startHour: hour, endHour: hour + 2 })
          }
        }
      } else {
        // 常规时间段（同一天内）
        for (let hour = nightStartHour; hour < nightEndHour - 1; hour += 2) {
          slots.push({ startHour: hour, endHour: hour + 2 })
        }
      }
      
      return slots
    }
    
    // 格式化小时为24小时制
    const formatHour = (hour) => {
      return `${hour.toString().padStart(2, '0')}:00`
    }
    
    // 估算天气（基于简单的日期模式）
    const estimateWeather = (date, hour) => {
      const dayOfWeek = date.getDay()
      const dayOfYear = Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24))
      
      // 使用简单的模式生成合理的天气估计
      const weatherTypes = ['晴朗', '少云', '多云']
      const weatherIndex = Math.floor((dayOfYear + hour) / 7) % weatherTypes.length
      
      // 增加一些随机性但保持一定模式
      const randomFactor = Math.random()
      if (randomFactor > 0.8) {
        return '晴朗' // 20%的概率特别晴朗
      }
      if (randomFactor < 0.2) {
        return '多云' // 20%的概率多云
      }
      
      return weatherTypes[weatherIndex]
    }
    
    // 计算时间评分
    const calculateHourScore = (hour, nightStartHour, nightEndHour) => {
      // 午夜附近通常是最佳观测时间
      if (hour >= 22 || hour <= 2) {
        return 9 // 接近午夜，最佳
      }
      if (hour >= 20 || hour <= 4) {
        return 7 // 较晚或较早，较好
      }
      return 5 // 其他时间一般
    }
    
    // 计算天气评分
    const calculateWeatherScore = (weather) => {
      switch (weather) {
        case '晴朗':
          return 9
        case '少云':
          return 7
        case '多云':
          return 5
        default:
          return 5
      }
    }
    
    // 获取时间槽样式类
    const getTimeSlotClass = (score) => {
      if (score >= 9) {
        return 'excellent'
      } else if (score >= 7) {
        return 'good'
      } else if (score >= 6) {
        return 'fair'
      } else {
        return 'poor'
      }
    }
    
    // 计算月球年龄（天数）
    const calculateMoonAge = (date) => {
      // 简单的月球年龄计算（真实应用中应使用更准确的算法）
      const lunarCycle = 29.53 // 月球周期约29.53天
      const referenceDate = new Date(2023, 0, 6) // 一个已知的新月日期
      const daysSinceReference = (date - referenceDate) / (1000 * 60 * 60 * 24)
      return (daysSinceReference % lunarCycle + lunarCycle) % lunarCycle
    }
    
    // 获取月球相位名称
    const getMoonPhaseName = (age) => {
      const phaseNames = ['新月', '眉月', '上弦月', '盈凸月', '满月', '亏凸月', '下弦月', '残月']
      const phaseIndex = Math.floor(age / 29.53 * 8)
      return phaseNames[phaseIndex % 8]
    }
    
    // 计算月球照明度
    const calculateMoonIllumination = (age) => {
      // 简化的照明度计算，真实应用中应使用更准确的算法
      const lunarCycle = 29.53
      return Math.sin((age / lunarCycle) * Math.PI * 2) * 0.5 + 0.5
    }
    
    // 更新最后更新时间
    const updateLastUpdated = () => {
      lastUpdated.value = new Date().toLocaleString('zh-CN')
    }
    
    // 初始化地图和可视化（简化版）
    const initializeVisualizations = () => {
      // 初始化月球可视化
      if (typeof initMoonVisualization === 'function') {
        initMoonVisualization();
      }
      // 初始化视宁度可视化
      initSeeingVisualization();
      // 初始化光污染地图
      initLightPollutionMap();
      console.log('初始化可视化组件')
    }
    
    // 初始化光污染地图
    const initLightPollutionMap = () => {
      if (lightPollutionMapRef.value) {
        // 清空占位符
        lightPollutionMapRef.value.innerHTML = '';
        
        // 创建地图容器
        const mapContainer = document.createElement('div');
        mapContainer.className = 'light-pollution-leaflet-map';
        lightPollutionMapRef.value.appendChild(mapContainer);
        
        // 尝试加载Leaflet（如果已通过CDN加载）
        if (window.L) {
          const map = window.L.map(mapContainer).setView([currentLocation.value.latitude, currentLocation.value.longitude], 8);
          
          // 添加基础地图图层
          window.L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; OpenStreetMap contributors'
          }).addTo(map);
          
          // 添加光污染图层（使用World Atlas of Artificial Night Sky Brightness数据）
          // 由于实际API限制，这里使用模拟的光污染数据图层
          const createLightPollutionLayer = () => {
            const canvasLayer = window.L.canvasOverlay({
              resizeDelay: 100,
              draw: function(canvas, params) {
                const ctx = canvas.getContext('2d');
                const { bounds, size } = params;
                
                // 清空画布
                ctx.clearRect(0, 0, size.x, size.y);
                
                // 模拟光污染数据点
                const centerLat = currentLocation.value.latitude;
                const centerLng = currentLocation.value.longitude;
                const intensity = observationData.lightPollution || 3;
                
                // 创建径向渐变表示光污染扩散
                const centerPixel = map.latLngToContainerPoint([centerLat, centerLng]);
                const gradient = ctx.createRadialGradient(
                  centerPixel.x, centerPixel.y, 0,
                  centerPixel.x, centerPixel.y, 200
                );
                
                // 根据光污染等级设置颜色
                let color1, color2, color3;
                if (intensity <= 2) { // 极佳
                  color1 = 'rgba(0, 0, 20, 0.1)';
                  color2 = 'rgba(0, 0, 50, 0.1)';
                  color3 = 'rgba(0, 0, 100, 0.1)';
                } else if (intensity <= 4) { // 良好
                  color1 = 'rgba(50, 50, 20, 0.2)';
                  color2 = 'rgba(100, 100, 50, 0.2)';
                  color3 = 'rgba(150, 150, 100, 0.2)';
                } else if (intensity <= 6) { // 一般
                  color1 = 'rgba(100, 50, 0, 0.3)';
                  color2 = 'rgba(150, 100, 0, 0.3)';
                  color3 = 'rgba(200, 150, 0, 0.3)';
                } else if (intensity <= 8) { // 较差
                  color1 = 'rgba(200, 100, 0, 0.4)';
                  color2 = 'rgba(220, 150, 0, 0.4)';
                  color3 = 'rgba(250, 200, 0, 0.4)';
                } else { // 很差
                  color1 = 'rgba(255, 200, 0, 0.5)';
                  color2 = 'rgba(255, 230, 0, 0.5)';
                  color3 = 'rgba(255, 255, 0, 0.5)';
                }
                
                gradient.addColorStop(0, color1);
                gradient.addColorStop(0.5, color2);
                gradient.addColorStop(1, color3);
                
                ctx.fillStyle = gradient;
                ctx.fillRect(0, 0, size.x, size.y);
                
                // 添加观测地点标记
                ctx.fillStyle = '#ff0000';
                ctx.beginPath();
                ctx.arc(centerPixel.x, centerPixel.y, 6, 0, Math.PI * 2);
                ctx.fill();
                
                ctx.strokeStyle = '#ffffff';
                ctx.lineWidth = 2;
                ctx.stroke();
              }
            });
            
            return canvasLayer;
          };
          
          // 添加光污染图层
          const lightPollutionLayer = createLightPollutionLayer();
          lightPollutionLayer.addTo(map);
          
          // 添加光污染图例
          const legend = window.L.control({
            position: 'bottomright'
          });
          
          legend.onAdd = function() {
            const div = window.L.DomUtil.create('div', 'light-pollution-legend');
            div.innerHTML = `
              <div class="legend-title">光污染等级</div>
              <div class="legend-item">
                <div class="legend-color excellent"></div>
                <span>1-2级 (极佳)</span>
              </div>
              <div class="legend-item">
                <div class="legend-color good"></div>
                <span>3-4级 (良好)</span>
              </div>
              <div class="legend-item">
                <div class="legend-color fair"></div>
                <span>5-6级 (一般)</span>
              </div>
              <div class="legend-item">
                <div class="legend-color poor"></div>
                <span>7-8级 (较差)</span>
              </div>
              <div class="legend-item">
                <div class="legend-color severe"></div>
                <span>9级 (很差)</span>
              </div>
            `;
            return div;
          };
          
          legend.addTo(map);
          
          // 监听位置变化，更新地图视图
          watch(() => currentLocation.value, (newLocation) => {
            if (newLocation.latitude && newLocation.longitude) {
              map.setView([newLocation.latitude, newLocation.longitude], 8);
              lightPollutionLayer.redraw();
            }
          }, { deep: true });
          
          // 监听光污染数据变化，更新图层
          watch(() => observationData.lightPollution, () => {
            lightPollutionLayer.redraw();
          });
          
          // 保存地图引用以便后续更新
          return map;
        } else {
          // Leaflet未加载，显示备用内容
          mapContainer.innerHTML = `
            <div class="map-placeholder">
              <div class="map-icon">🗺️</div>
              <span>光污染地图</span>
              <div class="light-pollution-info">
                <div>坐标: ${currentLocation.value.latitude.toFixed(4)}, ${currentLocation.value.longitude.toFixed(4)}</div>
                <div class="light-pollution-level">等级: ${observationData.lightPollution || '--'}/9</div>
              </div>
            </div>
          `;
        }
      }
    }
    
    // 开始数据更新
    const startUpdates = async () => {
      try {
        // 立即并行更新初始数据
        await Promise.all([
          updateISSData(),
          updateSolarData(),
          updateMoonData(),
          updateObservationData()
        ])
        
        // 等待其他数据更新完成后再更新最佳观测时间
        await updateBestViewingTimes()
        
        console.log('初始数据更新完成')
      } catch (error) {
        console.error('初始数据更新失败:', error)
      }
      
      // 设置定时更新
      updateInterval = setInterval(async () => {
        try {
          // 每10秒更新ISS位置
          await updateISSData()
          
          // 每分钟更新一次太阳和月球数据
          if (Date.now() % 60000 < 1000) {
            await Promise.all([
              updateSolarData(),
              updateMoonData()
            ])
          }
          
          // 每3分钟更新一次观测数据和最佳观测时间
          if (Date.now() % 180000 < 1000) {
            await updateObservationData()
            await updateBestViewingTimes()
          }
        } catch (error) {
          console.error('定时数据更新失败:', error)
        }
      }, 10000)
    }
    
    // 组件挂载
    onMounted(() => {
      initializeVisualizations()
      startUpdates()
    })
    
    // 组件卸载
    onUnmounted(() => {
      if (updateInterval) {
        clearInterval(updateInterval)
      }
      if (seeingAnimationFrame) {
        cancelAnimationFrame(seeingAnimationFrame);
      }
    })
    
    return {
      lastUpdated,
      issData,
      solarData,
      moonData,
      observationData,
      bestViewingTimes,
      issMapRef,
      moonPhaseRef,
      lightPollutionMapRef,
      userLocationInput,
      getTrendIcon,
      getFlareLevel,
      getFlareClass,
      getKpClass,
      getMoonPhaseStyle,
      getScoreClass,
      getTimeSlotClass,
      getDotClass,
      getPhaseTitle,
      getSeeingStatus,
      getSeeingDescription,
      handleImageError,
      updateLocation,
      useCurrentLocation
    }
  }
}
</script>

<style scoped>
.astronomical-data-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem 1rem;
  color: var(--text-primary);
}

/* 地理位置输入样式 */
.location-input {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1rem;
}

.location-text-input {
  flex: 1;
  padding: 0.5rem;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background: var(--bg-input);
  color: var(--text-primary);
  font-size: 0.875rem;
}

.location-submit-btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 6px;
  background: var(--accent-color);
  color: white;
  cursor: pointer;
  font-size: 0.875rem;
  transition: background 0.3s ease;
}

.location-submit-btn:hover {
  background: var(--accent-hover);
}

.location-current-btn {
  padding: 0.5rem 0.75rem;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background: var(--bg-button);
  cursor: pointer;
  font-size: 1rem;
  transition: all 0.3s ease;
}

.location-current-btn:hover {
  background: var(--bg-button-hover);
}

.data-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.section-title {
  font-size: 2rem;
  font-weight: 700;
  margin: 0;
  color: var(--text-primary);
}

.last-updated {
  font-size: 0.875rem;
  color: var(--text-secondary);
}

.data-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.data-card {
  background: var(--bg-card);
  border-radius: 16px;
  padding: 1.5rem;
  border: 1px solid var(--border-color);
  box-shadow: 0 4px 16px var(--shadow-color);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.data-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px var(--shadow-color);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid var(--border-color);
}

.card-icon {
  font-size: 2rem;
}

.card-title {
  font-size: 1.25rem;
  font-weight: 700;
  margin: 0;
  color: var(--text-primary);
}

.card-content {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

/* 视宁度可视化样式 */
.seeing-container {
  background: var(--bg-secondary);
  border-radius: 12px;
  padding: 1.5rem;
  margin-bottom: 1.5rem;
}

.seeing-container h4 {
  margin: 0 0 1rem 0;
  color: var(--text-primary);
  font-size: 1.125rem;
  font-weight: 600;
}

.seeing-content {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.seeing-value {
  font-size: 2rem;
  font-weight: 700;
  color: var(--accent-color);
  text-align: center;
}

.seeing-waveform {
  width: 100%;
  height: 120px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.seeing-canvas {
  width: 100%;
  height: 100%;
  display: block;
}

.seeing-info {
  text-align: center;
}

.seeing-status {
  font-size: 1.25rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
  color: var(--text-primary);
}

.seeing-description {
  font-size: 0.875rem;
  color: var(--text-secondary);
  line-height: 1.5;
}

/* ISS卡片样式 */
.iss-content {
  flex-direction: row;
  align-items: flex-start;
}

.iss-location {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.location-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.label {
  font-size: 0.875rem;
  color: var(--text-secondary);
}

.value {
  font-size: 1rem;
  font-weight: 600;
  color: var(--accent-color);
}

.iss-map {
  width: 200px;
  height: 200px;
  background: linear-gradient(135deg, #1a2a6c, #b21f1f, #fdbb2d);
  border-radius: 12px;
  position: relative;
  overflow: hidden;
}

/* 太阳活动卡片样式 */
.solar-content {
  flex-direction: row;
  align-items: flex-start;
  gap: 1.5rem;
}

.solar-indicators {
  flex: 1;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.indicator {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.indicator-label {
  font-size: 0.75rem;
  color: var(--text-secondary);
}

.indicator-value {
  font-size: 1.25rem;
  font-weight: 700;
  color: var(--text-primary);
}

.indicator-change {
  font-size: 1rem;
}

.indicator-change.increasing {
  color: #4caf50;
}

.indicator-change.decreasing {
  color: #f44336;
}

.flare-intensity {
  width: 100%;
  height: 4px;
  border-radius: 2px;
  background: #ccc;
  margin-top: 0.25rem;
}

.flare-quiet { background: #4caf50; }
.flare-low { background: #8bc34a; }
.flare-medium { background: #ffeb3b; }
.flare-high { background: #ff9800; }
.flare-active { background: #ff5722; }
.flare-severe { background: #f44336; }

.kp-indicator {
  width: 100%;
  height: 4px;
  border-radius: 2px;
  background: #ccc;
  margin-top: 0.25rem;
}

.kp-low { background: #4caf50; }
.kp-medium { background: #ffeb3b; }
.kp-high { background: #ff9800; }
.kp-severe { background: #f44336; }

.solar-image {
  width: 180px;
  height: 180px;
}

.sun-image {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  overflow: hidden;
  background: #ff9800;
  display: flex;
  align-items: center;
  justify-content: center;
}

.sun-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.sun-placeholder {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: linear-gradient(135deg, #ff9800, #f57c00);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 0.75rem;
}

.sun-icon {
  font-size: 3rem;
  margin-bottom: 0.5rem;
}

/* 月球相位卡片样式 */
.moon-content {
  gap: 1.5rem;
}

.moon-phase-display {
  display: flex;
  gap: 1.5rem;
}

.moon-model {
  width: 150px;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.moon-sphere {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: linear-gradient(135deg, #f5f5f5, #d7ccc8);
  position: relative;
  box-shadow: 0 0 20px rgba(255, 255, 255, 0.3);
}

.moon-sphere::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: linear-gradient(90deg, transparent 50%, rgba(0, 0, 0, 0.5) 50%);
  transform: translateX(-50%);
}

.moon-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.phase-name {
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--accent-color);
}

.phase-details {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.detail-item {
  display: flex;
  justify-content: space-between;
}

.moon-phase-calendar {
  width: 100%;
}

.calendar-dots {
  display: flex;
  justify-content: space-between;
  padding: 0.5rem;
  background: rgba(85, 136, 255, 0.05);
  border-radius: 8px;
}

.phase-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: var(--border-color);
  transition: all 0.3s ease;
}

.phase-dot.current-day {
  transform: scale(1.5);
  background: var(--accent-color);
}

.phase-dot.new-moon {
  background: #333;
}

.phase-dot.first-quarter,
.phase-dot.last-quarter {
  background: #999;
}

.phase-dot.full-moon {
  background: #f5f5f5;
  box-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
}

/* 观测条件卡片样式 */
.observation-content {
  flex-direction: row;
  gap: 1.5rem;
}

.observation-score {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.score-circle {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  color: white;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}

.score-excellent {
  background: linear-gradient(135deg, #4caf50, #8bc34a);
}

.score-good {
  background: linear-gradient(135deg, #2196f3, #03a9f4);
}

.score-fair {
  background: linear-gradient(135deg, #ff9800, #ff5722);
}

.score-poor {
  background: linear-gradient(135deg, #f44336, #d32f2f);
}

.score-number {
  font-size: 2rem;
}

.score-label {
  font-size: 0.875rem;
  opacity: 0.9;
}

.score-details {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.score-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.score-item .unit {
  font-size: 0.75rem;
  color: var(--text-secondary);
  margin-left: 0.25rem;
}

/* 详细评分样式 */
.detailed-scores {
  margin-top: 1.5rem;
  padding-top: 1rem;
  border-top: 1px solid var(--border-color);
}

.detailed-score-item {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin-bottom: 0.75rem;
}

.detailed-score-item .label {
  font-size: 0.75rem;
  color: var(--text-secondary);
  width: 60px;
}

.progress-bar {
  flex: 1;
  height: 6px;
  background: var(--bg-progress);
  border-radius: 3px;
  overflow: hidden;
  position: relative;
}

.progress-fill {
  height: 100%;
  border-radius: 3px;
  transition: width 0.3s ease;
}

.humidity-fill { background: linear-gradient(90deg, #ff5722, #4caf50); }
.wind-fill { background: linear-gradient(90deg, #4caf50, #ff9800, #f44336); }
.temperature-fill { background: linear-gradient(90deg, #4caf50, #ffeb3b, #ff5722); }
.moon-fill { background: linear-gradient(90deg, #4caf50, #ffeb3b, #f44336); }

.light-pollution-map {
  width: 200px;
  height: 200px;
  background: linear-gradient(135deg, #1a1a2e, #16213e, #0f3460);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  overflow: hidden;
  position: relative;
}

.light-pollution-leaflet-map {
  width: 100%;
  height: 100%;
  z-index: 1;
}

.light-pollution-info {
  margin-top: 0.5rem;
  font-size: 0.75rem;
  line-height: 1.4;
}

.light-pollution-level {
  margin-top: 0.25rem;
  font-weight: 600;
  color: #ffcc00;
}

/* 光污染图例样式 */
.light-pollution-legend {
  background: rgba(255, 255, 255, 0.9);
  padding: 8px;
  border-radius: 6px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  font-size: 11px;
  max-width: 120px;
}

.legend-title {
  font-weight: bold;
  margin-bottom: 6px;
  color: #333;
  font-size: 10px;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.legend-color {
  width: 12px;
  height: 12px;
  margin-right: 6px;
  border-radius: 2px;
  border: 1px solid rgba(0, 0, 0, 0.2);
}

.legend-color.excellent {
  background: linear-gradient(to right, rgba(0, 0, 20, 0.8), rgba(0, 0, 100, 0.3));
}

.legend-color.good {
  background: linear-gradient(to right, rgba(50, 50, 20, 0.8), rgba(150, 150, 100, 0.3));
}

.legend-color.fair {
  background: linear-gradient(to right, rgba(100, 50, 0, 0.8), rgba(200, 150, 0, 0.3));
}

.legend-color.poor {
  background: linear-gradient(to right, rgba(200, 100, 0, 0.8), rgba(250, 200, 0, 0.3));
}

.legend-color.severe {
  background: linear-gradient(to right, rgba(255, 200, 0, 0.8), rgba(255, 255, 0, 0.3));
}

/* 响应式调整 */
@media (max-width: 768px) {
  .light-pollution-map {
    width: 150px;
    height: 150px;
  }
  
  .light-pollution-legend {
    font-size: 10px;
    padding: 6px;
    max-width: 100px;
  }
}

.map-placeholder {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
}

.map-icon {
  font-size: 2.5rem;
}

/* 最佳观测时间样式 */
.best-time-section {
  margin-top: 2rem;
}

.section-subtitle {
  font-size: 1.5rem;
  font-weight: 700;
  margin: 0 0 1.5rem 0;
  color: var(--text-primary);
}

.best-time-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 1rem;
}

.time-slot {
  background: var(--bg-card);
  border-radius: 12px;
  padding: 1rem;
  border: 1px solid var(--border-color);
  transition: transform 0.3s ease;
}

.time-slot:hover {
  transform: translateY(-2px);
}

.slot-excellent {
  border-left: 4px solid #4caf50;
}

.slot-good {
  border-left: 4px solid #2196f3;
}

.slot-fair {
  border-left: 4px solid #ff9800;
}

.slot-poor {
  border-left: 4px solid #f44336;
}

.time-info {
  margin-bottom: 0.5rem;
}

.time-date {
  font-size: 1rem;
  font-weight: 600;
  color: var(--text-primary);
}

.time-range {
  font-size: 0.875rem;
  color: var(--text-secondary);
}

.time-score {
  font-size: 1.25rem;
  font-weight: 700;
  margin-bottom: 0.5rem;
}

.slot-excellent .time-score {
  color: #4caf50;
}

.slot-good .time-score {
  color: #2196f3;
}

.slot-fair .time-score {
  color: #ff9800;
}

.slot-poor .time-score {
  color: #f44336;
}

.time-conditions {
  display: flex;
  gap: 1rem;
}

.condition-item {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  font-size: 0.75rem;
  color: var(--text-secondary);
}

.condition-icon {
  font-size: 1rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .data-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
  
  .data-cards {
    grid-template-columns: 1fr;
  }
  
  .iss-content,
  .solar-content,
  .moon-phase-display,
  .observation-content {
    flex-direction: column;
    align-items: center;
  }
  
  .iss-map,
  .solar-image,
  .light-pollution-map {
    width: 100%;
    max-width: 200px;
  }
  
  .solar-indicators {
    grid-template-columns: 1fr;
    width: 100%;
  }
  
  .moon-info {
    align-items: center;
    text-align: center;
  }
  
  .best-time-container {
    grid-template-columns: 1fr;
  }
}
</style>